import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { HJMRequestInterceptors, HJMRequestConfig } from './type'
import { ElLoading } from 'element-plus'
import { ILoadingInstance } from 'element-plus/lib/components/loading/src/loading.type'

const DEFALE_LODING = true
//如果不止一个baseurl地址就可以这样封装
class HJMRequest {
  //创建axios实例
  instance: AxiosInstance
  interceptors?: HJMRequestInterceptors
  loading?: ILoadingInstance
  showLoading: boolean

  constructor(config: HJMRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? DEFALE_LODING
    //从config取出的拦截器是对应实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
    //所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在加载，请稍等...',
            background: 'rgba(0,0,0,.5)'
          })
        }
        console.log('所有实例都有的拦截器：请求拦截成功')
        return config
      },
      (err) => {
        console.log('所有实例都有的拦截器：请求拦截失败')
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        console.log('所有实例都有的拦截器：响应成功拦截')
        //讲loading移除
        setTimeout(() => {
          this.loading?.close()
        }, 1000)
        const data = res.data
        if (data.returnCode === '-1001') {
          console.log('请求失败，错误信息')
        } else {
          return data
        }
      },
      (err) => {
        if (err.response.status === 404) {
          console.log('404的错误')
        }
        return err
      }
    )
  }
  //每个请求对应的拦截
  request<T>(config: HJMRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          this.showLoading = DEFALE_LODING
          //将结果resolve返回出去
          resolve(res)
        })
        .catch((err) => {
          this.showLoading = DEFALE_LODING
          reject(err)
          return err
        })
    })
  }

  get<T>(config: HJMRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T>(config: HJMRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }

  delete<T>(config: HJMRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  patch<T>(config: HJMRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}
export default HJMRequest
